package ms.pms.service;

import ms.common.exception.BizException;
import ms.common.token.TokenUtil;
import ms.common.util.bean.BeanUtil;
import ms.common.util.string.StringUtil;
import ms.pms.bean.CommonQueryParamBean;
import ms.pms.bean.LoginParamBean;
import ms.pms.config.ResponseCode;
import ms.pms.dao.PermissionDAO;
import ms.pms.dao.RolePermissionDAO;
import ms.pms.dao.UserDAO;
import ms.pms.dao.UserRoleDAO;
import ms.pms.entity.Permission;
import ms.pms.entity.RolePermission;
import ms.pms.entity.User;
import ms.pms.entity.UserRole;
import ms.pms.vo.PermissionVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Project Name: ms
 * File Name: LoginService
 * Package Name: ms.pms.service
 * Date: 2018/6/21  18:22
 * Copyright (c) 2018, tianyul All Rights Reserved.
 */
@Service
public class LoginService {

    @Autowired
    private UserDAO userDAO;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PermissionDAO permissionDAO;

    @Autowired
    private UserRoleDAO userRoleDAO;

    @Autowired
    private RolePermissionDAO rolePermissionDAO;

    /**
     * 登录
     * @param loginParamBean
     * @return
     */
    public Map<String,Object> sign(LoginParamBean loginParamBean) {
        User userParam = new User();
        userParam.setAccount(loginParamBean.getAccount());
        userParam.setPwd(loginParamBean.getPwd());

        User user = userDAO.selectOne(userParam);
        if(null == user) {
            throw new BizException(ResponseCode.PARAM_ILLEGAL_ERROR, "用户名或密码错误");
        }
        if(2 == user.getStatus()) {
            throw new BizException(ResponseCode.PARAM_ILLEGAL_ERROR, "该账号已被停用，请联系管理员");
        }
        Long userId =  user.getId();
        String token = TokenUtil.createToken(userId + "");

        //获取用户权限列表
        List<Permission> permissions = getUserPersmission(userId);

        List<String> urls = new ArrayList<>();

        if(!StringUtil.isEmpty(permissions)) {
            permissions.forEach(permission -> {
                if(2 == permission.getType()) {
                    urls.add(permission.getUrl());
                }
            });
        }
        //放入缓存--redis
        Map<String,Object> users = redisTemplate.opsForHash().entries("ms-pms");
        if(StringUtil.isEmpty(users)) {
            users = new HashMap<>();
        }
        users.put(token, userId);
        users.put("pms_" + userId, urls);
        redisTemplate.opsForHash().putAll("ms-pms", users);

        Map<String,Object> result = new HashMap<>();
        result.put("token", token);
        result.put("menus", getMenus(userId));
        return result;
    }

    /**
     * 获得用户权限
     * @param userId
     */
    private List<Permission> getUserPersmission(Long userId) {
        //获取用户角色
        UserRole userRoleParam = new UserRole();
        userRoleParam.setUserId(userId);

        UserRole userRole = userRoleDAO.selectOne(userRoleParam);
        if(null == userRole) {
            return new ArrayList<>();
        }
        return permissionDAO.getPermissionsByRoleId(userRole.getRoleId());
    }
    /**
     * 权限列表
     * @param userId
     * @return
     */
    public List<PermissionVO> getMenus(Long userId) {
        //返回结果
        List<PermissionVO> permissionVOS = new ArrayList<>();
        //权限id集合
        List<Long> rolePermissionIds = new ArrayList<>();
        //获取用户角色
        UserRole userRoleParam = new UserRole();
        userRoleParam.setUserId(userId);

        UserRole userRole = userRoleDAO.selectOne(userRoleParam);
        if(null == userRole) {
            return new ArrayList<>();
        }
        //查询角色对应权限
        RolePermission rolePermissionParam = new RolePermission();
        rolePermissionParam.setRoleId(userRole.getRoleId());
        List<RolePermission> rolePermissions = rolePermissionDAO.select(rolePermissionParam);

        if(!StringUtil.isEmpty(rolePermissions)) {
            rolePermissions.forEach(rolePermission -> {
                rolePermissionIds.add(rolePermission.getPermissionId());
            });
        }

        //目前菜单最多2级，权限最多3级
        Permission pidParam = new Permission();
        pidParam.setPid(0L);
        //父菜单
        List<Permission> permissions = permissionDAO.select(pidParam);
        for (Permission permission : permissions) {
            //拷贝权限
            PermissionVO permissionVO = BeanUtil.copy(permission, PermissionVO.class);
            List<PermissionVO> permissionVOList = new ArrayList<>();
            pidParam.setPid(permission.getId());

            //2级菜单
            List<Permission> secondPermissions = permissionDAO.select(pidParam);
            for (Permission p: secondPermissions) {
                if(rolePermissionIds.contains(p.getId())) {
                    PermissionVO pvo = BeanUtil.copy(p, PermissionVO.class);
                    pvo.setChildren(null);
                    permissionVOList.add(pvo);
                }

            }
            permissionVO.setChildren(permissionVOList);
            permissionVOS.add(permissionVO);
        }

        return permissionVOS;
    }
}
